package com.bbcare.nutritious.plat.service.imp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.util.JSONUtils;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.HuamitechApiUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.nutritious.plat.entity.PtActivitiesDaily;
import com.bbcare.nutritious.plat.entity.PtHeartratesRecord;
import com.bbcare.nutritious.plat.entity.PtHuamiToken;
import com.bbcare.nutritious.plat.entity.PtSleepDaily;
import com.bbcare.nutritious.plat.service.IActivityHuamiService;
import com.bbcare.nutritious.plat.store.ibatis.IActivityHuamiDao;
import com.bbcare.nutritious.plat.store.ibatis.IBloodSugarDao;
/**
 * 
 * @name:         ActivityHuamiService.java
 * @author:       tao
 * @createTime:   2017年7月3日
 * @description:  运动  相关服务
 * @modify:
 *
 */
@Service
public class ActivityHuamiService implements IActivityHuamiService {

	public static final Logger logger = Logger.getLogger(ActivityHuamiService.class);

    @Autowired
    private IPatientService patientService;
    @Autowired
    private IActivityHuamiDao activityHuamiDao;
    @Autowired
    private IFollowQueueService fllowQueueService;
    @Autowired
    private IBloodSugarDao bloodSugarDao;
    
	@Override
	@Transactional
	public Map<String, Object> bindHuamiAccessToken(Map<String, Object> param)
			throws Exception {
    	logger.info("in bindHuamiAccessToken");
    	
    	String code = (String)param.get("code");
    	String userId = (String)param.get("userId");
    	String tenantId = "";
    	String deviceId = (String)param.get("deviceId");
    	String createTime = DateUtil.getSysDateA();
    	
    	List<Patient> ptList = patientService.getPatientList(param);
    	if(CollectionUtils.isEmpty(ptList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
	        			"随访用户信息不正确");
		}else{
			for(int i =0;i<ptList.size();i++){
				if(!Constants.PT_USER_INFO_DEFAULT_TENANT_ID.equals(ptList.get(i).getTenantId())){
					tenantId = ptList.get(i).getTenantId();
					break;
				}
			}
		}
    	
    	//根据code 查询token 
    	String accessToken ="";
    	String refreshToken ="";
    	Long expiresTime = null;
    	boolean flag = false;
    	
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(HuamitechApiUtil.CLIENT_ID, PropertiesUtils.getProperty(HuamitechApiUtil.CLIENT_ID)));
        params.add(new BasicNameValuePair(HuamitechApiUtil.CLIENT_SECRET,PropertiesUtils.getProperty(HuamitechApiUtil.CLIENT_SECRET)));
        params.add(new BasicNameValuePair(HuamitechApiUtil.REDIRECT_URI,PropertiesUtils.getProperty(HuamitechApiUtil.REDIRECT_URI)));
        params.add(new BasicNameValuePair(HuamitechApiUtil.GRANT_TYPE,"authorization_code"));
        params.add(new BasicNameValuePair(HuamitechApiUtil.CODE,code));
	        
	 	List<Header> headerList = new ArrayList<Header>();
	 	HuamitechApiUtil.addAuthHeader(headerList);
        
        Map<String,String> rspMap = HuamitechApiUtil.postAuthorization(HuamitechApiUtil.TOKEN_URL,params,headerList);
        if(org.apache.commons.collections.MapUtils.isNotEmpty(rspMap)){
        	String statusCode = rspMap.get("statusCode");
        	String result = rspMap.get("result");
        	if(HuamitechApiUtil.status_success.equals(statusCode) && !StringUtils.isBlank(result) && JSONUtils.mayBeJSON(result)){
        		JSONObject json = JSON.parseObject(result);
        		accessToken = json.getString(HuamitechApiUtil.ACCESS_TOKEN);
        		refreshToken = json.getString(HuamitechApiUtil.REFRESH_TOKEN);
        		expiresTime = json.getLong("expires_in");
        		if(!StringUtils.isBlank(accessToken) && !StringUtils.isBlank(refreshToken)){
        			flag = true;//获取token成功
        		}
        	}
        }
        
    	//如果token获取成功 则绑定 并提示绑定成功
    	if(flag){
    		//判断是否已经绑定  已经绑定则修改 未绑定 则直接绑定
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("userId",userId);
    		map.put("tenantId",tenantId);
    		map.put("status",Constants.COMMON_STATUS_NOMAL);
    		
    		List<PtHuamiToken> token = activityHuamiDao.selectHuamiTokenByUserId(map);
    		if(!CollectionUtils.isEmpty(token)){
    			map.clear();
    			map.put("id",token.get(0).getId());
        		map.put("accessToken",accessToken);
        		map.put("refreshToken",refreshToken);
        		map.put("expiresTime",expiresTime);
        		map.put("updateTime",createTime);
        		map.put("huamiId",deviceId);
        		activityHuamiDao.updatePtHuamiToken(map);
    		}else{
    			PtHuamiToken ptToken = new PtHuamiToken();
        		ptToken.setAccessToken(accessToken);
        		ptToken.setCreateAuthor(userId);
        		ptToken.setCreateTime(createTime);
        		ptToken.setExpiresTime(expiresTime);
        		ptToken.setHuamiId(deviceId);
        		ptToken.setId(SeqUtil.getSeqNo());
        		ptToken.setRefreshToken(refreshToken);
        		ptToken.setUserId(userId);
        		ptToken.setTenantId(tenantId);
        		ptToken.setStatus(Constants.COMMON_STATUS_NOMAL);
        		List<PtHuamiToken> tokens = new ArrayList<PtHuamiToken>();
        		tokens.add(ptToken);
        		activityHuamiDao.savePtHuamiToken(tokens);
    		}
    	}else{
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_HUAMI_GETTOKEN_FAIL,"华米手环授权失败");
    	}
    	logger.info("out bindHuamiAccessToken");
		return null;
	}
	
	@Override
	public JSONObject refreshHuamiAccessToken(Map<String, Object> param)
			throws Exception {
		logger.info("in refreshHuamiAccessToken");
    	String oldRefreshToken =(String)param.get("refreshToken");
    	String id = (String)param.get("id");
    	
    	String createTime = DateUtil.getSysDateA();

    	String accessToken ="";
    	String refreshToken ="";
    	Long expiresTime = null;
    	boolean flag = false;
    	
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(HuamitechApiUtil.CLIENT_ID, PropertiesUtils.getProperty(HuamitechApiUtil.CLIENT_ID)));
        params.add(new BasicNameValuePair(HuamitechApiUtil.CLIENT_SECRET,PropertiesUtils.getProperty(HuamitechApiUtil.CLIENT_SECRET)));
        params.add(new BasicNameValuePair(HuamitechApiUtil.GRANT_TYPE,HuamitechApiUtil.REFRESH_TOKEN));
	        
	 	List<Header> headerList = new ArrayList<Header>();
	 	
    	headerList.add(new BasicHeader("Authorization","Bearer "+oldRefreshToken));
	 	HuamitechApiUtil.addAuthHeader(headerList);
        
	 	JSONObject json = null;
        Map<String,String> tokenMap = HuamitechApiUtil.postAuthorization(HuamitechApiUtil.REFRESH_TOKEN_URL,params,headerList);
        if(org.apache.commons.collections.MapUtils.isNotEmpty(tokenMap)){
        	logger.info("刷新token返回 ："+JSON.toJSONString(tokenMap));
        	String statusCode = tokenMap.get("statusCode");
        	String result = tokenMap.get("result");
        	if(HuamitechApiUtil.status_success.equals(statusCode) && !StringUtils.isBlank(result) && JSONUtils.mayBeJSON(result)){
        		json = JSON.parseObject(result);
        		accessToken = json.getString(HuamitechApiUtil.ACCESS_TOKEN);
        		refreshToken = json.getString(HuamitechApiUtil.REFRESH_TOKEN);
        		expiresTime = json.getLong("expires_in");
        		if(!StringUtils.isBlank(accessToken) && !StringUtils.isBlank(refreshToken)){
        			flag = true;//获取token成功
        		}
        	}
        }
        
        if(flag){
        	Map<String,Object> map = new HashMap<String,Object>();
        	map.put("id",id);
    		map.put("accessToken",accessToken);
    		map.put("refreshToken",refreshToken);
    		map.put("expiresTime",expiresTime);
    		map.put("updateTime",createTime);
    		activityHuamiDao.updatePtHuamiToken(map);
    		
        }
		return json;
	}
	
	@Override
	/**
	 *  
	 * @param param accessToken refreshToken id
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public Map<String, Object> synchActivities(Map<String, Object> param)
			throws Exception {
		logger.info("in synchActivities");
		String createTime = DateUtil.getSysDateA();
		
		String deleteRecordId = (String)param.get("recordId");
		
    	String accessToken =(String)param.get("accessToken");
    	String userId =(String)param.get("userId");
    	String tenantId =(String)param.get("tenantId");
    	String startDate = (String)param.get("startDate");
    	String endDate = (String)param.get("endDate");
    	String interval = (String)param.get("interval");

    	
    	//根据token查询步数  
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(new BasicNameValuePair("startDate",startDate));
  		params.add(new BasicNameValuePair("endDate",endDate));
  		params.add(new BasicNameValuePair("interval",interval));
  		
  		List<Header> headerList = new ArrayList<Header>();
    	headerList.add(new BasicHeader("Authorization","Bearer "+accessToken));
	 	HuamitechApiUtil.addApiHeader(headerList);
	 	Map<String,String> humaiMap = null;
	 	
		//如果返回token失效 或 不存在 则刷新token 
	 	humaiMap = HuamitechApiUtil.getHuamiData(HuamitechApiUtil.ACTIVITIES_PATH, params, headerList);
	 	if(HuamitechApiUtil.status_token_error.equals(humaiMap.get("statusCode"))){
	 		JSONObject json = this.refreshHuamiAccessToken(param);
	 		if(null != json){
	 			accessToken = json.getString(HuamitechApiUtil.ACCESS_TOKEN);
	 			headerList.clear();
	 			headerList.add(new BasicHeader("Authorization","Bearer "+accessToken));
	 		 	HuamitechApiUtil.addApiHeader(headerList);
	 		 	humaiMap = HuamitechApiUtil.getHuamiData(HuamitechApiUtil.ACTIVITIES_PATH, params, headerList);
	 		}
	 	}
	 	
	 	List<PtActivitiesDaily> list = new ArrayList<PtActivitiesDaily>();
	 	
	 	if(!MapUtils.isEmpty(humaiMap)){
	 		if(HuamitechApiUtil.status_success.equals(humaiMap.get("statusCode"))){
	 			String result = humaiMap.get("result");
	        	if(!StringUtils.isBlank(result) && JSONUtils.mayBeJSON(result)){
	        		JSONObject obj = JSONObject.parseObject(result);
	        		JSONArray arr = obj.getJSONArray("items");
	        		if(null != arr){
	        			for(int i =0;i<arr.size();i++){
	        				JSONObject temp = arr.getJSONObject(i);
	        				PtActivitiesDaily activity = new PtActivitiesDaily();
	        				activity.setId(SeqUtil.getSeqNo());
	        				activity.setCalories(temp.getIntValue("calories"));
	        				activity.setCreateTime(createTime);
	        				activity.setDistance(temp.getIntValue("distance"));
	        				activity.setRundistance(temp.getIntValue("runDistance"));
	        				activity.setSteps(temp.getIntValue("steps"));
	        				activity.setTestDate(temp.getDate("date"));
	        				activity.setTenantId(tenantId);
	        				activity.setUserId(userId);
	        				activity.setSourceState("2");
	        				list.add(activity);
	        				//判断这天是否存在app上用户录入的数据，有则清除
	        				Map<String,Object> stepmap = Collections.synchronizedMap(new HashMap<String,Object>());
	        		    	stepmap.put("userId", activity.getUserId());
	        		    	stepmap.put("tenantId", tenantId);
	        		    	stepmap.put("testDate", activity.getTestDate());
	        		    	List<Map<String,Object>> steplist = activityHuamiDao.getStepForDate(stepmap);
	        		    	if(!CollectionUtils.isEmpty(steplist)){//不存在，插入
	        		    		Map<String,Object> map = new HashMap<String,Object>();
	        		 			map.put("id", steplist.get(0).get("ID")); //删除
	        		 			activityHuamiDao.deleteLastActivitiesDaily(map);
	        		    	}
	        			}
	        		}
	        	}
	 		}else{
	 			//获取数据失败
	 		}
	 	}
	 	if(!CollectionUtils.isEmpty(list)){
	 		//
	 		if(!StringUtils.isBlank(deleteRecordId)){
	 			Map<String,Object> map = new HashMap<String,Object>();
	 			map.put("id", deleteRecordId); //先删除最后一天记录
	 			activityHuamiDao.deleteLastActivitiesDaily(map);
	 		}
	 		
	 		activityHuamiDao.savePtActivitiesDaily(list);
	 	}
	 	
		return null;
	}
	@Override
	@Transactional
	public Map<String, Object> synchHeartrates(Map<String, Object> param)
			throws Exception {
		logger.info("in synchHeartrates");
		String createTime = DateUtil.getSysDateA();
		String userId =(String)param.get("userId");
    	String tenantId =(String)param.get("tenantId");
    	String accessToken =(String)param.get("accessToken");
    	String startDate = (String)param.get("startDate");
    	String endDate = (String)param.get("endDate");
    	
    	
    	//根据token查询步数  
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(new BasicNameValuePair("startDate",startDate));
  		params.add(new BasicNameValuePair("endDate",endDate));
  		
  		List<Header> headerList = new ArrayList<Header>();
    	headerList.add(new BasicHeader("Authorization","Bearer "+accessToken));
    	HuamitechApiUtil.addApiHeader(headerList);
	 	Map<String,String> humaiMap = null;
	 	
		//如果返回token失效 或 不存在 则刷新token 
	 	humaiMap = HuamitechApiUtil.getHuamiData(HuamitechApiUtil.HEARTRATES_PATH, params, headerList);
	 	if(HuamitechApiUtil.status_token_error.equals(humaiMap.get("statusCode"))){
	 		JSONObject json = this.refreshHuamiAccessToken(param);
	 		if(null != json){
	 			accessToken = json.getString(HuamitechApiUtil.ACCESS_TOKEN);
	 			headerList.clear();
	 			headerList.add(new BasicHeader("Authorization","Bearer "+accessToken));
	 			HuamitechApiUtil.addApiHeader(headerList);
	 			param.put("",accessToken);
	 		 	humaiMap = HuamitechApiUtil.getHuamiData(HuamitechApiUtil.HEARTRATES_PATH, params, headerList);
	 		}
	 	}
	 	
	 	List<PtHeartratesRecord> list = new ArrayList<PtHeartratesRecord>();
	 	if(!MapUtils.isEmpty(humaiMap)){
	 		if(HuamitechApiUtil.status_success.equals(humaiMap.get("statusCode"))){
	 			String result = humaiMap.get("result");
	        	if(!StringUtils.isBlank(result) && JSONUtils.mayBeJSON(result)){
	        		JSONObject obj = JSONObject.parseObject(result);
	        		JSONArray arr = obj.getJSONArray("items");
	        		if(null != arr){
	        			System.out.println("PtHeartratesRecord ---"+arr.size());
	        			for(int i =0;i<arr.size();i++){
	        				JSONObject temp = arr.getJSONObject(i);
	        				PtHeartratesRecord heart = new PtHeartratesRecord();
	        				heart.setId(SeqUtil.getSeqNo());
	        				heart.setTestDate(temp.getDate("date"));
	        				heart.setCreateTime(createTime);
	        				heart.setTestMinute(temp.getIntValue("minute"));
	        				heart.setHeartrate(temp.getIntValue("heartRateData"));
	        				heart.setTenantId(tenantId);
	        				heart.setUserId(userId);
	        				list.add(heart);
	        			}
	        		}
	        	}
	 		}else{
	 			//获取数据失败
	 		}
	 	}
	 	if(!CollectionUtils.isEmpty(list)){
	 		int batchCount = 1000;// 每批commit的个数
            int batchLastIndex = batchCount;// 每批最后一个的下标
            for (int index = 0; index < list.size();) {
                if (batchLastIndex >= list.size()) {
                    batchLastIndex = list.size();
                    activityHuamiDao.savePtHeartratesRecord(list.subList(index, batchLastIndex));
                    break;// 数据插入完毕，退出循环
                } else {
                	activityHuamiDao.savePtHeartratesRecord(list.subList(index, batchLastIndex));
                    index = batchLastIndex;// 设置下一批下标
                    batchLastIndex = index + batchCount;
                }
            }
	 	}
		return null;
	}
	
	@Override
	@Transactional
	public Map<String, Object> synchSleep(Map<String, Object> param)
			throws Exception {
		logger.info("in synchSleep");
		String createTime = DateUtil.getSysDateA();
		
		String deleteRecordId = (String)param.get("recordId");
		
    	String accessToken =(String)param.get("accessToken");
    	String userId =(String)param.get("userId");
    	String tenantId =(String)param.get("tenantId");
    	String startDate = (String)param.get("startDate");
    	String endDate = (String)param.get("endDate");
    	String interval = (String)param.get("interval");
    	
    	//根据token查询步数  
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(new BasicNameValuePair("startDate",startDate));
  		params.add(new BasicNameValuePair("endDate",endDate));
  		params.add(new BasicNameValuePair("interval",interval));
  		
  		List<Header> headerList = new ArrayList<Header>();
	 	
    	headerList.add(new BasicHeader("Authorization","Bearer "+accessToken));
    	HuamitechApiUtil.addApiHeader(headerList);
	 	Map<String,String> humaiMap = null;
	 	
		//如果返回token失效 或 不存在 则刷新token 
	 	humaiMap = HuamitechApiUtil.getHuamiData(HuamitechApiUtil.SLEEP_PATH, params, headerList);
	 	if(HuamitechApiUtil.status_token_error.equals(humaiMap.get("statusCode"))){
	 		JSONObject json = this.refreshHuamiAccessToken(param);
	 		if(null != json){
	 			accessToken = json.getString(HuamitechApiUtil.ACCESS_TOKEN);
	 			headerList.clear();
	 			headerList.add(new BasicHeader("Authorization","Bearer "+accessToken));
	 			HuamitechApiUtil.addApiHeader(headerList);
	 		 	humaiMap = HuamitechApiUtil.getHuamiData(HuamitechApiUtil.SLEEP_PATH, params, headerList);
	 		}
	 	}
	 	
	 	List<PtSleepDaily> list = new ArrayList<PtSleepDaily>();
	 	
	 	if(!MapUtils.isEmpty(humaiMap)){
	 		if(HuamitechApiUtil.status_success.equals(humaiMap.get("statusCode"))){
	 			String result = humaiMap.get("result");
	        	if(!StringUtils.isBlank(result) && JSONUtils.mayBeJSON(result)){
	        		JSONObject obj = JSONObject.parseObject(result);
	        		JSONArray arr = obj.getJSONArray("items");
	        		if(null != arr){
	        			for(int i =0;i<arr.size();i++){
	        				JSONObject temp = arr.getJSONObject(i);
	        				PtSleepDaily sleep = new PtSleepDaily();
	        				sleep.setId(SeqUtil.getSeqNo());
	        				sleep.setCreateTime(createTime);
	        				sleep.setTestDate(temp.getDate("date"));
	        				sleep.setTenantId(tenantId);
	        				sleep.setUserId(userId);
	        				sleep.setDeepsleeptime(temp.getIntValue("deepSleepTime"));
	        				sleep.setShallowsleeptime(temp.getIntValue("shallowSleepTime"));
	        				sleep.setStart(temp.getIntValue("start"));
	        				sleep.setStop(temp.getIntValue("stop"));
	        				sleep.setWaketime(temp.getIntValue("wakeTime"));
	        				list.add(sleep);
	        			}
	        		}
	        	}
	 		}else{
	 			//获取数据失败
	 		}
	 	}
	 	if(!CollectionUtils.isEmpty(list)){
	 		//最后一天数据 可能不全  先删除 再入表
	 		if(!StringUtils.isBlank(deleteRecordId)){
	 			Map<String,Object> map = new HashMap<String,Object>();
	 			map.put("id", deleteRecordId); //先删除最后一天记录
	 			activityHuamiDao.deleteLastSleepDaily(map);
	 		}
	 		activityHuamiDao.savePtSleepDaily(list);
	 	}
	 	
		return null;
	}
	
	@Override
	public List<Map<String, Object>> getPatientAuthorizationList(
			Map<String, Object> paramMap) throws Exception {
		logger.info("in getPatientAuthorizationList");
		
		List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
		String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;
		
		List<String> queueIdArray = new ArrayList<String>();
		if(StringUtils.isEmpty(queueId)){
			// 根据当前登录账号获取，其可以查看的队列id
			queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
			if(CollectionUtils.isEmpty(queueIdArray)){
				logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
				return list;
			}
		}else{
			queueIdArray.add(queueId);
		}
		
        paramMap.put("queueIdIn",queueIdArray);
        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
        
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start",page);
		paramMap.put("end", rows);
		
		Object userNameObject = paramMap.get("userName");
		Object userName = !org.springframework.util.StringUtils.isEmpty(userNameObject) ? "%"+userNameObject.toString()+"%" : userNameObject ; 
		paramMap.put("userName",userName);
		
		Object phoneNo = paramMap.get("phoneNo");
		paramMap.put("phoneNo",phoneNo);
		
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		list = activityHuamiDao.selectPtHuamiTokenMapList(paramMap);
		
		Map<String, Object> map =null;
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				map = list.get(i);
				if(null != map.get("createTime")){
					list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
				}
				if(null == map.get("authStatus")){
					list.get(i).put("authStatus","0");
				}
				map = null;
			}
		}
		return list;
	}
	
	@Override
	public int getPatientAuthorizationCount(
			Map<String, Object> paramMap) throws Exception {
		return activityHuamiDao.selectPtHuamiTokenMapCount(paramMap);
	}
	
	@Override
	public Map<String, Object> synchProfile(Map<String, Object> param)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> synchAllData(Map<String, Object> param)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> getActivityPatientList(
			Map<String, Object> paramMap) throws Exception {
			logger.info("in getActivityPatientList");
			
			List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
			String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;
			
			List<String> queueIdArray = new ArrayList<String>();
			if(StringUtils.isEmpty(queueId)){
				// 根据当前登录账号获取，其可以查看的队列id
				queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
				if(CollectionUtils.isEmpty(queueIdArray)){
					logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
					return list;
				}
			}else{
				queueIdArray.add(queueId);
			}
			
	        paramMap.put("queueIdIn",queueIdArray);
	        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
	        
			int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
			int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
			
			paramMap.put("start", rows*(page-1));
			paramMap.put("end", rows);
			
			Object userNameObject = paramMap.get("searchCondition");
			Object searchCondition = !org.springframework.util.StringUtils.isEmpty(userNameObject) ? "%"+userNameObject.toString()+"%" : userNameObject ; 
			paramMap.put("searchCondition",searchCondition);
			
			list = activityHuamiDao.selectActivityPatientList(paramMap);
			String testDate = null;
			Map<String, Object> map =null;
			if(!CollectionUtils.isEmpty(list)){
				for(int i = 0;i<list.size();i++){
					map = list.get(i);
					if(null != map.get("testDate")){
						testDate = map.get("testDate").toString();
						list.get(i).put("testDate",testDate);
						list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
					}
					map = null;
				}
			}
			return list;
	}

	@Override
	public int getActivityPatientCount(Map<String, Object> paramMap)
			throws Exception {
		return activityHuamiDao.selectActivityPatientCount(paramMap);
	}

	@Override
	public List<Map<String, Object>> getSleepPatientList(Map<String, Object> paramMap)
			throws Exception{
		logger.info("in getSleepPatientList");
		
		List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
		String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;
		
		List<String> queueIdArray = new ArrayList<String>();
		if(StringUtils.isEmpty(queueId)){
			// 根据当前登录账号获取，其可以查看的队列id
			queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
			if(CollectionUtils.isEmpty(queueIdArray)){
				logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
				return list;
			}
		}else{
			queueIdArray.add(queueId);
		}
		
        paramMap.put("queueIdIn",queueIdArray);
        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
        
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start", rows*(page-1));
		paramMap.put("end", rows);
		
		Object userNameObject = paramMap.get("searchCondition");
		Object searchCondition = !org.springframework.util.StringUtils.isEmpty(userNameObject) ? "%"+userNameObject.toString()+"%" : userNameObject ; 
		paramMap.put("searchCondition",searchCondition);
		
		list = activityHuamiDao.selectSleepPatientList(paramMap);
		String testDate = null;
		Map<String, Object> map =null;
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				map = list.get(i);
				if(null != map.get("testDate")){
					testDate = map.get("testDate").toString();
					list.get(i).put("testDate",testDate);
					list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
				}
				map = null;
			}
		}
		return list;
	}

	@Override
	public int getSleepPatientCount(Map<String, Object> paramMap)
			throws Exception {
		return activityHuamiDao.selectSleepPatientCount(paramMap);
	}

	@Override
	public Map<String, Object> getHuamiAuthUrl(Map<String, Object> param)
			throws Exception {
		
    	String userId = (String)param.get("userId");
//    	String tenantId = (String)param.get("tenantId");
//    	String deviceId = (String)param.get("deviceId");
    	
    	List<Patient> ptList = patientService.getPatientList(param);
    	if(CollectionUtils.isEmpty(ptList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
	        			"随访用户信息不正确");
		}
    	
    	Map<String,Object> urlMap= new HashMap<String,Object>();
    	urlMap.put("userId",userId);
//		urlMap.put("tenantId",tenantId);
//		urlMap.put("deviceId",deviceId);
		String url = HuamitechApiUtil.buildHuamiUrl(urlMap);
		
		Map<String,Object> rspMap= new HashMap<String,Object>();
  		rspMap.put("redirectUrl",url);  //二维码code地址
  		
		return rspMap;
	}

	@Override
	public Map<String, Object> getHuamiDataListByUserId(
			Map<String, Object> paramMap) throws Exception {
		String type =(String)paramMap.get("type");
				
		Map<String,Object> rspMap = new HashMap<String,Object>();
		Map<String,Object>  usermap = new HashMap<String,Object>();
		usermap.put("userId", paramMap.get("userId"));
		usermap.put("tenantId", paramMap.get("tenantId"));
//		map.put("status","1"));
		Patient patient = patientService.getPatient(usermap);
		
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
        			"患者信息不存在");		}
		
		rspMap.put("birthday",patient.getBirthday());
		rspMap.put("pregnancyWeek",patient.getPregnancyDay());
		rspMap.put("userName",patient.getUserName());
		rspMap.put("gender",patient.getGender());
		rspMap.put("phoneNo",patient.getPhoneNo());
		rspMap.put("userId",paramMap.get("userId"));
		
		//查询绑定设备和状态 
		usermap.clear();
		usermap.put("userId",paramMap.get("userId"));
		usermap.put("status",Constants.COMMON_STATUS_NOMAL);
		usermap.put("type",Constants.DEVICE_TYPE_SPORT);
		usermap.put("tenantId",paramMap.get("tenantId"));
		List<Map<String,Object>> deviceRefList = bloodSugarDao.selectDeviceRefList(usermap);
		if(CollectionUtils.isEmpty(deviceRefList)){
			rspMap.put("bindStatus", "0");
		}else{
			rspMap.put("bindStatus", deviceRefList.get(0).get("status"));
			rspMap.put("id", deviceRefList.get(0).get("id"));
			rspMap.put("deviceId", deviceRefList.get(0).get("deviceId"));
		}
		
		//查询授权状态 
//		selectHuamiTokenByUserId
		List<PtHuamiToken> tokenList = activityHuamiDao.selectHuamiTokenByUserId(usermap);
		if(CollectionUtils.isEmpty(tokenList)){
			rspMap.put("status", "0");
		}else{
			rspMap.put("status", tokenList.get(0).getStatus());
		}
		
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start", rows*(page-1));
		paramMap.put("end", rows);
		
		List<Map<String, Object>>  list = null;
		if(Constants.HUAMI_TYPE_ACTIVITIES.equals(type)){
			list = activityHuamiDao.selectActivitiesList(paramMap);
		}else if(Constants.HUAMI_TYPE_SLEEP.equals(type)){
			list = activityHuamiDao.selectSleepList(paramMap);
		}
		
		String testDate = null;
		Map<String, Object> map =null;
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				map = list.get(i);
				if(null != map.get("testDate")){
					testDate = map.get("testDate").toString();
					list.get(i).put("testDate",testDate);
					list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
				}
				map = null;
			}
		}
		
		rspMap.put("recordList", list);
		return rspMap;
	}
}
